package com.opdar.athena.web.service;

import com.opdar.athena.entities.ProjectEntity;
import com.opdar.athena.mapper.*;
import com.opdar.platform.utils.AES;
import com.opdar.platform.utils.MD5;
import com.opdar.platform.utils.SHA1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

/**
 * Created by shiju on 2017/1/27.
 */
@Service
public class ProjectService {
    @Autowired
    private ProjectMapper projectMapper;
    @Autowired
    private UserService userService;

    public List<ProjectEntity> selectAll() {
        return projectMapper.selectList(null);
    }

    public ProjectEntity selectById(String projectId) {
        ProjectEntity query = new ProjectEntity();
        query.setId(projectId);
        return projectMapper.selectOne(query);
    }

    @Transactional(rollbackFor = Throwable.class)
    public boolean insert(String name,String domain) {
        ProjectEntity projectEntity = new ProjectEntity();
        projectEntity.setId(UUID.randomUUID().toString());
        projectEntity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        projectEntity.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        projectEntity.setAppId(UUID.randomUUID().toString().replaceAll("-",""));
        projectEntity.setSalt(UUID.randomUUID().toString().replaceAll("-",""));
        projectEntity.setAppSecret(SHA1.encrypt(projectEntity.getAppId()+projectEntity.getSalt()));
        projectEntity.setName(name);
        projectEntity.setDomain(domain);
        int ret = projectMapper.insert(projectEntity);
        return ret > 0;
    }

    @Transactional(rollbackFor = Throwable.class)
    public boolean update(String name, String projectId,String domain) {
        ProjectEntity where = new ProjectEntity();
        where.setId(projectId);
        ProjectEntity update = new ProjectEntity();
        update.setName(name);
        update.setDomain(domain);
        int ret = projectMapper.update(update, where);
        return ret>0;
    }

    public boolean delete(String projectId) {
        ProjectEntity project = new ProjectEntity();
        project.setId(projectId);
        int ret = projectMapper.delete(project);
        return ret > 0;
    }
}
